<template>
  <div>
    <van-nav-bar title="余额充值" left-arrow @click-left="onClickLeft"/>
    <div class="split-title">选择充值金额</div>
    <van-cell-group inset>
      <van-cell>
        <ul class="recharge-list">
          <li
            v-for="(item, index) in schemeDetailed"
            :key="index"
            :class="{active: activeIndex === index}"
            @click="selectRecharge(item, index)"
          >
            <i>¥{{item.recharge_price}}</i> <span>元</span>
            <div class="give" v-if="rechargeScheme.isGive === 1">赠 {{item.give_price}}</div>
          </li>
        </ul>
      </van-cell>
      <van-field v-if="rechargeScheme.isFreePrice === 1" v-model="freePrice" @change="onFreePriceChange" type="digit" :min="1" :max="1000" label="自定义金额" placeholder="请输入要充值的金额" />
    </van-cell-group>
    <div class="block">
      <van-button type="primary" size="large" @click="goRecharge">充值</van-button>
    </div>
    <div class="block" style="text-align: center">
      充值：{{recharge.rechargePrice || 0}} 元<span v-if="rechargeScheme.isGive === 1">，赠送：{{recharge.givePrice || 0}} 元</span>
    </div>
  </div>
</template>

<script>
import Utils from '../utils'
export default {
  name: 'Recharge',
  components: {},
  props: [],
  data () {
    return {
      freePrice: null,
      activeIndex: null,
      recharge: {
        rechargePrice: '',
        givePrice: ''
      },
      wePayInfo: {
        appId: '', // 公众号名称，由商户传入
        timeStamp: '', // 时间戳，自1970年以来的秒数
        nonceStr: '', // 随机串
        package: '',
        signType: '', // 微信签名方式：
        paySign: '' // 微信签名
      },
      aliPayAction: '',
      aliPayValue: ''
    }
  },
  computed: {
    rechargeScheme () {
      return this.$store.state.user?.rechargeScheme || {}
    },
    schemeDetailed () {
      return JSON.parse(this.rechargeScheme.schemeDetailed || '')
    }
  },
  created () {
  },
  mounted () {},
  watch: {},
  methods: {
    onClickLeft () {
      this.$router.push('/')
    },
    selectRecharge (item, index) {
      this.activeIndex = index
      this.freePrice = null
      this.recharge.rechargePrice = item.recharge_price
      this.recharge.givePrice = item.give_price
    },
    onFreePriceChange () {
      if (this.freePrice * 1 >= 1) {
        this.freePrice = this.freePrice * 1
        this.activeIndex = null
        this.recharge.rechargePrice = (this.freePrice * 1) + ''
        this.recharge.givePrice = null
      } else {
        this.freePrice = null
        this.activeIndex = null
        this.recharge.rechargePrice = null
        this.recharge.givePrice = null
      }
    },
    goRecharge () {
      if (Utils.isNull(this.recharge.rechargePrice)) {
        this.$notify({ type: 'danger', message: '请选择一个充值金额！' })
        return
      }
      if (parseInt(this.recharge.rechargePrice) < 1) {
        this.$notify({ type: 'danger', message: '充值金额至少1元！' })
        return
      }
      if (this.rechargeScheme.isGive === 0) {
        this.recharge.givePrice = null
      }
      // 调用微信支付请求
      this.$http.post('/system/recharge_record/goRecharge', this.$qs.stringify(this.recharge)).then(res => {
        if (res.code === 200) {
          if (typeof WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(res.data), false)
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(res.data))
              document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(res.data))
            }
          } else {
            this.onBridgeReady(res.data)
          }
        } else {
          this.$toast.fail(res.msg)
        }
      })
    },
    // 将支付的认证和回调 封装成函数
    onBridgeReady: function (payInfo) {
      const that = this
      // eslint-disable-next-line no-undef
      WeixinJSBridge.invoke(
        // 微信支付的一些认证  需要去网站设置好  然后在这调用
        /* eslint-disable */
        'getBrandWCPayRequest', {
          "appId": payInfo.appId, // 公众号名称，由商户传入
          "timeStamp": payInfo.timeStamp, // 时间戳，自1970年以来的秒数
          "nonceStr": payInfo.nonceStr, // 随机串
          "signType": payInfo.signType,
          "package": payInfo.package, // 微信签名方式：
          "paySign": payInfo.paySign // 微信签名
        },
        /* eslint-enable */
        function (res) {
          // 这个是支付成功的回调
          // eslint-disable-next-line eqeqeq
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            that.$toast.success('充值成功！')
            that.onClickLeft()
            that.$store.dispatch('updateUserInfo')
          } else {
          }
        })
    }
  }
}
</script>

<style scoped lang='less'>
.recharge-list {
  display: flex; flex-wrap: wrap; justify-content: space-between;
  li {
    box-sizing: border-box;
    width: 32%;
    padding: 5px 5px; margin: 5px 0;
    border: solid 1px #ddd; border-radius: 4px;
    line-height: 18px;
    &.active {
      border: solid 1px #08e;
      box-shadow: 0 0 2px rgba(#08e, 1) inset;
    }
    & > span {
      font-size: 10px;
    }
    & > i {
      color: #09f; font-weight: bold; font-size: 17px;
    }
    .give {
      display: block;
      font-size: 12px; color: #f60;
    }
  }
}
</style>
